package com.lucian.ge.controller.shopportal;

import com.alibaba.fastjson.JSONObject;
import com.lucian.ge.auth.controller.GetAuthController;
import com.lucian.ge.comman.model.ResultMap;
import com.lucian.ge.comman.model.ResultMapSyn;
import com.lucian.ge.service.shop.OrderService;
import com.lucian.ge.util.wxpay.sdk.MyConfig;
import com.lucian.ge.util.wxpay.sdk.WXPay;
import com.lucian.ge.util.wxpay.sdk.WXPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by Lucicol on 2019/7/23.
 */
@Api(value = "WxPayController", description = "wxpay-微信支付接口")

@RestController
@RequestMapping("/wxpay")
public class WxPayController {
    private final ResultMap resultMap;

    @Autowired(required=false)
    private OrderService orderService;

    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.apikey}")
    private String apikey;

    @Autowired
    public WxPayController(ResultMap resultMap) {
        this.resultMap = resultMap;
    }
    @ApiOperation(value="创建统一订单", notes="微信小程序")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="header", name = "token", value = "token", required = false, dataType = "String")
    })
    @PostMapping("/create")
    @ResponseBody
    public ResultMap create(
            @RequestHeader String token,
            @RequestParam(value = "userid") Integer userId,
            @RequestParam(value = "openid") String openId,
            @RequestParam(value = "order_no") String orderNo
//            @RequestParam(value = "total_fee") String payment
    ) throws Exception {
        if (!GetAuthController.getUserAuth(token, userId).equals("普通注册用户验证通过")) {
            return resultMap.success().code(301).message(GetAuthController.getUserAuth(token, userId)).token("").res("").data(null);
        }
        Map<String, String>  orderDetail = orderService.getOrderDetail(userId, orderNo);
        BigDecimal bd1 = new BigDecimal(String.valueOf(orderDetail.get("payment")));
        BigDecimal bd2 = new BigDecimal("100");
//        double paymentd = bd1.multiply(bd2).doubleValue();
//        String paymentd = bd1.multiply(bd2).toPlainString();
        String payment = bd1.multiply(bd2).setScale(0,BigDecimal.ROUND_DOWN).toPlainString();
//        System.out.println("payment"+ payment);
        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config);

        Map resultMap2=new HashMap();

        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String spbill_create_ip = addr.getHostAddress();

        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "好区多C端-商城订单支付");
        data.put("out_trade_no", orderNo);
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", payment);
        data.put("spbill_create_ip", spbill_create_ip);
        data.put("notify_url", "https://www.hatchdo.com");
        data.put("trade_type", "JSAPI");
        data.put("openid", openId);
//        "openid":"oqB4d5Gmk4y0sFvmgK-AIbCZ5g6o"
//        data.put("product_id", "12");
//        System.out.println(data);

        try {
            Map<String, String> rMap = wxpay.unifiedOrder(data);
//            System.out.println("统一下单接口返回: " + rMap);
            String return_code = (String) rMap.get("return_code");
            String result_code = (String) rMap.get("result_code");
            String nonceStr = WXPayUtil.generateNonceStr();
            resultMap2.put("nonceStr", nonceStr);
            Long timeStamp = System.currentTimeMillis() / 1000;
//            System.out.println(String.valueOf(timeStamp));
            if ("SUCCESS".equals(return_code) && return_code.equals(result_code)) {
                String prepayid = rMap.get("prepay_id");
                resultMap2.put("package", "prepay_id="+prepayid);
                resultMap2.put("signType", "MD5");
                resultMap2.put("timeStamp", timeStamp + "");
                resultMap2.put("appId",appid);

//                System.out.println("resultMap2 : "+ resultMap2);

                String sign = WXPayUtil.generateSignature(resultMap2, apikey);
                resultMap2.put("paySign", sign);
//                System.out.println("生成的签名paySign : "+ sign);
                return resultMap.success().code(200).message("预支付订单成功").token("").res(resultMap2).data(null);

            }else{
                return resultMap.success().code(400).message("预支付订单失败").token("").res("").data(null);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultMap.success().code(200).message("订单创建成功").token("").res("").data(null);
    }
}
